package com.kang.service;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.kang.bean.Dialogue;
import com.kang.bean.SocketMsg;
import com.kang.bean.Users;
import com.kang.service.userService.DialogueService;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 使用springboot的唯一区别是要@Component声明，而使用独立容器是由容器自己管理websocket的，
 * 但在springboot中连容器都是spring管理的。
 * 虽然@Component默认是单例模式的，但springboot还是会为每个websocket连接初始化一个bean，
 * 所以可以用一个静态set保存起来
 */
@Component
@ServerEndpoint(value = "/public/websocket/{nickname}/{toUserId}")
public class WebSocketService {

    public static UserService userService;
    public static DialogueService dialogueService;

    private String nickname;
    private Session session;
    //用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketService> webSocketSet = new CopyOnWriteArraySet<WebSocketService>();
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    //用来记录sessionId和该session进行绑定
    private static Map<String, Session> map = new HashMap<String, Session>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public synchronized  void onOpen(Session session, @PathParam("nickname") Long fromUserId, @PathParam("toUserId") Long toUserId) {
        Map<String,Object> message=new HashMap<String, Object>();
        this.session = session;
        Users users = userService.getUsersById(fromUserId);
        this.nickname = users.getName();
        //this.nickname = fromUserId.toString();
        map.put("" + fromUserId + toUserId, session);
        webSocketSet.add(this);//加入set中
        System.out.println("有新连接加入:" + nickname + ",当前在线人数为" + webSocketSet.size());
        //this.session.getAsyncRemote().sendText("恭喜" + nickname + "成功连接上WebSocket(其频道号：" + session.getId() + ")-->当前在线人数为：" + webSocketSet.size());
        message.put("type",0); //消息类型，0-连接成功，1-用户消息
        message.put("people",webSocketSet.size()); //在线人数
        message.put("name",fromUserId); //发送人id
        message.put("aisle",session.getId()); //频道号
        synchronized (this.session) {
            this.session.getAsyncRemote().sendText(new Gson().toJson(message));
        }
        List<Dialogue> list = dialogueService.getNotReadDialogue(toUserId,fromUserId);

        list.forEach(dialogue -> {
            message.put("type",1);
            message.put("name",dialogue.getFromUserId());
            message.put("msg",dialogue.getMsg());
            synchronized (this.session) {
                try {
                    this.session.getBasicRemote().sendText(new Gson().toJson(message));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        dialogueService.saveRead(list);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this); //从set中删除
        System.out.println("有一连接关闭！当前在线人数为" + webSocketSet.size());
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public synchronized  void onMessage(String message, Session session, @PathParam("nickname") Long fromUserId, @PathParam("toUserId") Long toUserId) {
        System.out.println("来自客户端的消息-->" + nickname + ": " + message);

        //从客户端传过来的数据是json数据，所以这里使用jackson进行转换为SocketMsg对象，
        // 然后通过socketMsg的type进行判断是单聊还是群聊，进行相应的处理:
        ObjectMapper objectMapper = new ObjectMapper();
        SocketMsg socketMsg;

        try {
            socketMsg = objectMapper.readValue(message, SocketMsg.class);
            if (socketMsg.getType() == 1) {
                //单聊.需要找到发送者和接受者.
                socketMsg.setFromUser("" + fromUserId + toUserId);//发送者.
                Session fromSession = map.get(socketMsg.getFromUser());
                Session toSession = map.get(socketMsg.getToUser());

                Map<String,Object> m=new HashMap<String, Object>();
                m.put("type",1);
                m.put("name",fromUserId);
                m.put("msg",socketMsg.getMsg());
                synchronized (fromSession) {
                    fromSession.getBasicRemote().sendText(new Gson().toJson(m));
                }
                //发送给接受者.
                if (toSession != null && toSession.isOpen()) {
                    //对方在线
                    synchronized (toSession) {
                        toSession.getBasicRemote().sendText(new Gson().toJson(m));
                    }
                    dialogueService.saveDialogue(fromUserId, toUserId,socketMsg.getMsg(), 0, 1, 0);
                } else {
                    //对方不在线
                    m.put("name",-1);
                    m.put("msg", "系统消息：对方不在线或对方未在您的消息窗口");
                    synchronized (fromSession) {
                        try {
                            fromSession.getBasicRemote().sendText(new Gson().toJson(m));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    //未读
                    dialogueService.saveDialogue(fromUserId, toUserId,socketMsg.getMsg(), 0, 1, 1);
                }
            } else {
                //群发消息
                broadcast(nickname + ": " + socketMsg.getMsg());
            }

        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }

    /**
     * 群发自定义消息
     */
    public void broadcast(String message) {
        for (WebSocketService item : webSocketSet) {
            item.session.getAsyncRemote().sendText(message);//异步发送消息.
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        WebSocketService that = (WebSocketService) o;
        return Objects.equals(nickname, that.nickname);
    }

    @Override
    public int hashCode() {
        return Objects.hash(nickname);
    }
}

